package calificaciones;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sistemas.sam.R;
import android.app.Activity;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

public class CalificacionesActivity extends Activity implements OnClickListener {
	JSONArray jArray = null;
	String result = null;
	String matricula, materia_nom;
	InputStream is = null;
	StringBuilder sb = null;
	String grupo2 = "";
	String dirr;
	String[] materias;
	String[] grupo_id;
	String php, variable, valor, campo;
	Intent i;
	private ConectarSam mAuthTask = null;

	Button altaC, modificarC;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_menu_calificaciones);

		altaC = (Button) findViewById(R.id.btn_alta);
		modificarC = (Button) findViewById(R.id.btn_modificar);
		modificarC.setOnClickListener(this);

		altaC.setOnClickListener(this);
		link l = new link();
		dirr = l.linkGrupoProfesor;
		php = "grupo_calif";
		valor = "20110TI001";
		variable = "id";
		campo = "grupo";
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_menu_calificaciones, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btn_alta) {
			i = new Intent(this, Datos_Calificacion.class);
			mAuthTask = new ConectarSam();
			mAuthTask.execute((Void) null);
		}
		if (v.getId() == R.id.btn_modificar) {
			i = new Intent(this, Busqueda_Alumno.class);
			mAuthTask = new ConectarSam();
			mAuthTask.execute((Void) null);
		}
	}

	private void abrirDashboard() {
		i.putExtra("grupo", materias);
		i.putExtra("grupoID", grupo_id);
		startActivity(i);
	}

	public class ConectarSam extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			// http post
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(dirr + variable + "=" + valor);
				Log.v("log_tag", dirr + php + ".php?" + variable + "=" + valor);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			} catch (Exception e) {
				Log.e("log_tag", " " + e.toString());
			}
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");

				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
				Log.v(" obtenido", result);
			} catch (Exception e) {
				Log.e("log_tag",
						"Error convirtiendo datos recibidos" + e.toString());
			}
			try {
				jArray = new JSONArray(result);
				JSONObject json_data = null;
				materias = new String[jArray.length()];
				grupo_id = new String[jArray.length()];
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					materias[i] = json_data.getString(campo);
					grupo_id[i] = json_data.getString("grupo_id");
					Log.d("msg", "paso  " + materias[i]);
					Log.d("grupo_id", "paso  " + grupo_id[i]);
				}
			} catch (JSONException e1) {
				Log.e("JSON ERR", e1.getMessage());
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			// showProgress(false);
			Log.v("login_resultado", success.toString());
			if (success) {

				abrirDashboard();

			} else {

			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			// showProgress(false);
		}
	}

}